<html>
<body>

<?php
echo "<form action=calculator.php method=post>";
echo "Type an expression into the following box. <br>";
echo "<input type=textbox name=equation value=\""
. $_POST["equation"] . "\"></input>";
echo "<input type=submit  value=Calculate></form><br>";

$rawexpr=$_POST["equation"];
$rnum="\-?[0-9]*\.?[0-9]+";
$rsp="[\s]*";
$rop="[\/\*\-\+]";

$regexp="/^(" . $rsp . $rnum . $rsp . $rop.")*".$rsp.$rnum.$rsp."$/";

$divzeroexp = "/\/".$rsp."0+([^1-9]*".$rop."|[^1-9]*$)/";

if(strlen($rawexpr) > 0){
if(preg_match($regexp,$rawexpr)){
	if(!preg_match($divzeroexp,$rawexpr)){	
		$expr= "\$res=".$rawexpr.";";		
		eval($expr);
	}
	else{
		$res="Divide by Zero.";
	}	
}
else{
	$res="Invalid Expression";
}
echo "<b>Calculation</b><br>". $rawexpr. "=". $res . "<br>";
}
?>
<br>
</body>
</html>
